package com.nanjia.boot.myflow.order.controller;

import cn.hutool.json.JSONUtil;
import cn.idev.excel.EasyExcel;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nanjia.boot.common.annotation.Log;
import com.nanjia.boot.common.enums.LogModuleEnum;
import com.nanjia.boot.common.enums.OrderStatusEnum;

import com.nanjia.boot.common.excelhandler.ExcelCellMergeStrategy;
import com.nanjia.boot.common.excelhandler.MultiColumnMergeStrategy;
import com.nanjia.boot.common.result.PageResult;
import com.nanjia.boot.common.result.Result;
import com.nanjia.boot.common.util.IPUtils;
import com.nanjia.boot.commonservice.CommonServiceImpl;
import com.nanjia.boot.core.security.util.SecurityUtils;
import com.nanjia.boot.myflow.order.dto.OrderDTO;
import com.nanjia.boot.myflow.order.model.form.OodForm;
import com.nanjia.boot.myflow.order.model.form.OrderForm;
import com.nanjia.boot.myflow.order.model.form.ReturnOrderForm;
import com.nanjia.boot.myflow.order.model.query.OrderQuery;
import com.nanjia.boot.myflow.order.model.vo.OrderVO;
import com.nanjia.boot.system.model.dto.UserExportDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单主前端控制层
 *
 * @author 周洋
 * @since 2025-07-11 11:49
 */
@Tag(name = "订单主接口")
@RestController
@RequestMapping("/api/v1/order")
@RequiredArgsConstructor
@Slf4j
public class OrderController {

    private final CommonServiceImpl commonMyFlowService;

    @Operation(summary = "导出订单")
    @GetMapping("/export")
    //@PreAuthorize(@ss.hasPerm('sys:user:export')")
    @Log(value = "导出用户", module = LogModuleEnum.USER)
    public void exportOrder(OrderQuery queryParams, HttpServletResponse response) throws IOException {
//        queryParams.setStatus(OrderStatusEnum.Status3.getValue());
        List<Integer> statusList = new ArrayList<>();
        statusList.add(OrderStatusEnum.Status3.getValue());
        statusList.add(OrderStatusEnum.Status11.getValue());
        queryParams.setStatuss(statusList);
        String fileName = "商城订单_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + SecurityUtils.getUserCode() + ".xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        List<OrderDTO> orderDTOList = commonMyFlowService.orderDTOList(queryParams);
        EasyExcel.write(response.getOutputStream(), OrderDTO.class).sheet("sheet1")
                .registerWriteHandler(new MultiColumnMergeStrategy(OrderDTO.class, orderDTOList))
                .doWrite(orderDTOList);
    }

    @Operation(summary = "订单主分页列表")
    @GetMapping("/page")
    public PageResult<OrderVO> getOrderPage(OrderQuery queryParams) {
        queryParams.getExcludeV().add(OrderStatusEnum.CART.getValue());
        queryParams.setUserId(SecurityUtils.getUserId());
        IPage<OrderVO> result = commonMyFlowService.getOrderPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "新增订单主")
    @PostMapping
    public Result<Void> saveOrder(@RequestBody @Valid OrderForm formData) {
        boolean result = commonMyFlowService.saveOrder(formData);
        return Result.judge(result);
    }

    @Operation(summary = "新增订单主")
    @PostMapping("createOrder")
    public Result<Void> createOrder(@RequestBody @Validated OrderForm formData, HttpServletRequest request) {
        log.info("createOrder:{}", JSONUtil.toJsonStr(formData));
        Result result = commonMyFlowService.createOrder(formData, IPUtils.getIpAddr(request));
        return result;
    }

    @Operation(summary = "修改订单状态订单主")
    @PostMapping("updateOrderStatus")
    public Result<Void> updateOrderStatus(@RequestBody @Validated OrderForm formData, HttpServletRequest request) {
        Result result = commonMyFlowService.updateOrderStatus(formData, IPUtils.getIpAddr(request));
        return result;
    }

    @Operation(summary = "修改订单状态订单主")
    @PostMapping("updateEmsStatus")
    public Result<Void> updateEmsStatus(@RequestBody @Validated OodForm formData, HttpServletRequest request) {
        Result result = commonMyFlowService.updateEmsStatus(formData, IPUtils.getIpAddr(request));
        return result;
    }

    @Operation(summary = "退货")
    @PostMapping("returnOrder")
    public Result<Object> returnOrder(@RequestBody @Validated List<ReturnOrderForm> returnOrderForms, HttpServletRequest request) {
        log.info("returnOrder:{}", JSONUtil.toJsonStr(returnOrderForms));
        return commonMyFlowService.returnOrder(returnOrderForms, IPUtils.getIpAddr(request));

    }

    /**
     * 再来一单
     *
     * @param formData
     * @param request
     * @return
     */
    @Operation(summary = "新增订单主")
    @PostMapping("createOrderByOld")
    public Result<Void> createOrderByOld(@RequestBody OrderForm formData, HttpServletRequest request) {
        boolean result = commonMyFlowService.createOrderByOld(formData, IPUtils.getIpAddr(request));
        return Result.judge(result);
    }

    @Operation(summary = "获取订单主表单数据")
    @GetMapping("/{id}/form")
    public Result<OrderForm> getOrderForm(
            @Parameter(description = "订单主ID") @PathVariable Long id
    ) {
        OrderForm formData = commonMyFlowService.getOrderFormData(id);
        return Result.success(formData);
    }

    @Operation(summary = "修改订单主")
    @PutMapping(value = "/{id}")
    public Result<Void> updateOrder(
            @Parameter(description = "订单主ID") @PathVariable Long id,
            @RequestBody @Validated OrderForm formData
    ) {
        boolean result = commonMyFlowService.updateOrder(id, formData);
        return Result.judge(result);
    }

    @Operation(summary = "删除订单主")
    @DeleteMapping("/{ids}")
    public Result<Void> deleteOrders(
            @Parameter(description = "订单主ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = commonMyFlowService.deleteOrders(ids);
        return Result.judge(result);
    }

    @Operation(summary = "获取订单")
    @GetMapping("/getCartOrderFormByUser")
    public Result<OrderForm> getCartOrderFormByUser(HttpServletRequest request) {
        OrderForm orderForm = commonMyFlowService.getCartOrderFormByUser(IPUtils.getIpAddr(request));
        return Result.success(orderForm);
    }


}
